package com.study.notepad.controller;/*
 @Author Cedar
 @DESCRIPTION 
*/

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.study.notepad.bean.Note;
import com.study.notepad.bean.User;
import com.study.notepad.service.NoteService;
import com.study.notepad.service.impl.NoteServiceImpl;
import com.study.notepad.util.ExcelUtil;
import com.study.notepad.util.PageUtil;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/note/*")
public class NoteServlet extends BaseServlet {

    private NoteService noteService = new NoteServiceImpl();

    public void queryByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idString = request.getParameter("id");
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        PageUtil pageUtil = new PageUtil(pageSize, pageNum);
        int id = Integer.parseInt(idString);
        List<Note> list = noteService.queryByUserId(id, pageUtil);
        Integer totalNum = noteService.totalNum(id);
        pageUtil.setData(list);
        pageUtil.setTotal(totalNum);
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        String json = gson.toJson(pageUtil);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
    }

    public void saveNote(HttpServletRequest request, HttpServletResponse response) {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        noteService.saveNote(loginUser.getId(), title, content);

        HashMap<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("msg", "保存成功");
        dataMap.put("url", "userInfo.jsp");
        forwardPage(request, response, dataMap, "/forward.jsp");
    }

    public void deleteById(HttpServletRequest request, HttpServletResponse response) {
        String idString = request.getParameter("id");
        int id = Integer.parseInt(idString);
        noteService.deleteById(id);

        HashMap<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("msg", "删除成功");
        dataMap.put("url", "userInfo.jsp");
        forwardPage(request, response, dataMap, "/forward.jsp");
    }

    public void updateById(HttpServletRequest request, HttpServletResponse response) {
        String idString = request.getParameter("id");
        int id = Integer.parseInt(idString);
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        noteService.updateById(id, title, content);

        HashMap<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("msg", "修改成功");
        dataMap.put("url", "userInfo.jsp");
        forwardPage(request, response, dataMap, "/forward.jsp");
    }

    public void queryById(HttpServletRequest request, HttpServletResponse response) {
        String idString = request.getParameter("id");
        int id = Integer.parseInt(idString);
        Note note = noteService.queryById(id);

        HashMap<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("note", note);
        forwardPage(request, response, dataMap, "/note.jsp");
    }


    public void downExcel(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<List<String>> dataList = new ArrayList<>();
        String idString = request.getParameter("id");
        int id = Integer.parseInt(idString);
        List<Note> list = noteService.queryByUserId(id, null);
        for (Note note : list) {
            List<String> data = new ArrayList<>();
            data.add(note.getId().toString());
            data.add(note.getTitle());
            data.add(note.getContent());
            data.add(dateFormat.format(note.getCreateDate()));
            data.add(dateFormat.format(note.getUpdateDate()));
            dataList.add(data);
        }
        Workbook workbook = ExcelUtil.createNoteExcel(dataList);
        String fileName = "文章列表.xlsx";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/ms-excel;charset=utf-8");
        response.setHeader("content-Disposition", "attachment;filename=" + fileName);
        try {
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void forwardPage(HttpServletRequest request, HttpServletResponse response,
                             Map<String, Object> data, String url) {
        for (Map.Entry entry : data.entrySet()) {
            String key = (String) entry.getKey();
            request.setAttribute(key, entry.getValue());
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
}
